package top.went.service;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import sun.applet.Main;
import top.went.db.dao.QuoteDao;
import top.went.db.dao.QuoteDetailDao;
import top.went.db.dao.UserDao;
import top.went.db.mapper.QuoteMapper;
import top.went.exception.NotFoundException;
import top.went.exception.ServiceException;
import top.went.pojo.QuoteDetailEntity;
import top.went.pojo.QuoteEntity;
import top.went.pojo.SaleOppEntity;
import top.went.utils.CodeGenerator;
import top.went.utils.TrackLog;
import top.went.vo.PageEntity;
import top.went.vo.QuoteDetail;
import top.went.vo.QuoteVo;

import java.math.BigDecimal;
import java.util.*;

/**
 * 报价
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class QuoteService {
    @Autowired
    private QuoteDao quoteDao;
    @Autowired
    private QuoteMapper quoteMapper;
    @Autowired
    private QuoteDetailDao quoteDetailDao;
    @Autowired
    private QuoteDetailService quoteDetailService;
    @Autowired
    private SaleOppService saleOppService;
    @Autowired
    private UserDao userDao;

    private static final Map<String,String> map = new HashMap<>();

    static {
        map.put("quoteId","quote_id");
        map.put("quoteTime","quote_time");
        map.put("totalQuote","total_quote");
        map.put("tbCustomerByCusId.cusName","cus_name");
    }


    /**
     * 新增报价单
     * @param quoteEntity
     * @return
     * @throws ServiceException
     */
    public boolean add(QuoteEntity quoteEntity) throws ServiceException {
        try {
            if(quoteEntity.getTbUserByUserId() == null || quoteEntity.getTbUserByUserId().getUserId() == null){
                quoteEntity.setTbUserByUserId(null);
            }
            if(quoteEntity.getTbContactsBy接收人Id() == null || quoteEntity.getTbContactsBy接收人Id().getCotsId() == null){
                quoteEntity.setTbContactsBy接收人Id(null);
            }
            if(quoteEntity.getTbCustomerByCusId() == null || quoteEntity.getTbCustomerByCusId().getCusId() == null){
                quoteEntity.setTbCustomerByCusId(null);
            }
            if(quoteEntity.getTbSaleOppByOppId() == null || quoteEntity.getTbSaleOppByOppId().getOppId() == null){
                quoteEntity.setTbSaleOppByOppId(null);
            }else {
                Long oppId = quoteEntity.getTbSaleOppByOppId().getOppId();
                SaleOppEntity saleOppEntity = saleOppService.load(oppId);
                String trackLog = TrackLog.getTrack(saleOppEntity,"商务谈判").toString();
                saleOppEntity.setStage("商务谈判");
                saleOppEntity.setTrackLog(trackLog);
                saleOppEntity.setStageStartTime(new java.sql.Date(new Date().getTime()));
                saleOppService.modifySaleOpp(saleOppEntity);
            }
            quoteEntity.setQuoteNumber(CodeGenerator.orderGenerator(false));
            return quoteDao.save(quoteEntity) != null;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("新增失败！");
        }
    }

    /**
     * 修改报价
     * @param quoteEntity
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean modify(QuoteEntity quoteEntity) throws NotFoundException, ServiceException {
        QuoteEntity quoteEntity1 = load(quoteEntity.getQuoteId());
        if(quoteEntity1.getApprovalStatus() != 0L && quoteEntity1.getApprovalStatus() != 3L){
            throw new ServiceException("报价单已锁定！");
        }
        quoteEntity1.setQuoteTheme(quoteEntity.getQuoteTheme());
//        quoteEntity1.setQuoteNumber(quoteEntity.getQuoteNumber());
        quoteEntity1.setClassification(quoteEntity.getClassification());
        quoteEntity1.setQuoteTime(quoteEntity.getQuoteTime());
        quoteEntity1.setTotalQuote(quoteEntity.getTotalQuote());
        quoteEntity1.setQuotationContact(quoteEntity.getQuotationContact());
        quoteEntity1.setRemarks(quoteEntity.getRemarks());
        quoteEntity1.setAnnex(quoteEntity.getAnnex());
        if(quoteEntity.getTbSaleOppByOppId() != null && quoteEntity.getTbSaleOppByOppId().getOppId() != null){
            quoteEntity1.setTbSaleOppByOppId(quoteEntity.getTbSaleOppByOppId());
        }
        if(quoteEntity.getTbCustomerByCusId() != null && quoteEntity.getTbCustomerByCusId().getCusId() != null){
            quoteEntity1.setTbCustomerByCusId(quoteEntity.getTbCustomerByCusId());
        }
        if(quoteEntity.getTbContactsBy接收人Id() != null && quoteEntity.getTbContactsBy接收人Id().getCotsId() != null){
            quoteEntity1.setTbContactsBy接收人Id(quoteEntity.getTbContactsBy接收人Id());
        }
        if(quoteEntity.getTbUserByUserId() != null && quoteEntity.getTbUserByUserId().getUserId() != null){
            quoteEntity1.setTbUserByUserId(quoteEntity.getTbUserByUserId());
        }
        try {
            quoteDao.save(quoteEntity1);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException("修改失败！");
        }
    }

    /**
     * 删除报价
     * @param id
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean delete(Long id) throws NotFoundException, ServiceException {
        QuoteEntity quoteEntity = load(id);
        List<QuoteDetailEntity> quoteDetailEntities = (List<QuoteDetailEntity>) quoteEntity.getTbQuoteDetailsByQuoteId();
        if(quoteDetailEntities != null && quoteDetailEntities.size() > 0){
            for(QuoteDetailEntity quoteDetailEntity : quoteDetailEntities){
                quoteDetailEntity.setIsDelete(1L);
            }
        }
        quoteEntity.setIsDelete(1L);
        try {
            quoteDao.save(quoteEntity);
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            throw new ServiceException();
        }
    }

    /**
     * 编辑删除
     * @param ids
     * @return
     * @throws NotFoundException
     * @throws ServiceException
     */
    public boolean deleteSelected(Long[] ids) throws NotFoundException, ServiceException {
        for(int i=0;i<ids.length;i++){
            delete(ids[i]);
        }
        return true;
    }

    /**
     * 加载报价
     * @param id
     * @return
     * @throws NotFoundException
     */
    public QuoteEntity load(Long id) throws NotFoundException {
        QuoteEntity quoteEntity = quoteDao.findAllByQuoteIdAndIsDelete(id, 0L);
        if(quoteEntity == null){
            throw new NotFoundException("不存在！");
        }
        return quoteEntity;
    }

    /**
     * 报价高级查询
     * @param quoteVo
     * @return
     */
    public PageEntity<QuoteEntity> findAllSeniorSearch(QuoteVo quoteVo){
        String order = quoteVo.getPage().getSort(map);
        if(order.length() <= 0){
            order = "quote_id desc";
        }
        Page<QuoteEntity> page = PageHelper.startPage(quoteVo.getPage().getPage(), quoteVo.getPage().getSize(), order+" nulls last");
        quoteMapper.findAllSeniorSearch(quoteVo);
        return new PageEntity<>(page.getTotal(),page.getResult());
    }

    /**
     * 根据报价id获取报价视图
     * @param id
     * @return
     */
    public QuoteEntity loadDetailById(Long id) throws NotFoundException {
        QuoteEntity quoteEntity = quoteMapper.loadDetailById(id);
        Double totalCost = 0.0;
        if(quoteEntity != null && quoteEntity.getTbQuoteDetailsByQuoteId() != null){
            Iterator it = quoteEntity.getTbQuoteDetailsByQuoteId().iterator();
            while (it.hasNext()){
                QuoteDetailEntity quoteDetailEntity = (QuoteDetailEntity) it.next();
                if(quoteDetailEntity != null ){
                    Double cost = quoteDetailEntity.getQdCost() == null ? 0.0 : quoteDetailEntity.getQdCost();
                    Double unitPrice = quoteDetailEntity.getUnitPrice() == null ? 0.0 : quoteDetailEntity.getUnitPrice();
                    Double amount = quoteDetailEntity.getAmount() == null ? 1 : quoteDetailEntity.getAmount();
                    totalCost += amount * (unitPrice - cost);
                }
            }
            quoteEntity.setExpectedProfit(totalCost);
        }
        if(quoteEntity == null){
            throw new NotFoundException("未找到！");
        }
        return quoteEntity;
    }

    /**
     * 加载报价对应明细
     * @param id
     * @return
     * @throws NotFoundException
     */
    public List<QuoteDetail> loadDetail(Long id) throws NotFoundException {
        List<QuoteDetailEntity> quoteDetailEntities = quoteDetailDao.findAll(id);
        if (quoteDetailEntities == null) {
            throw new NotFoundException("未找到！");
        }
        List<QuoteDetail> quoteDetails = new ArrayList<>();
        for(QuoteDetailEntity quoteDetailEntity : quoteDetailEntities){
            QuoteDetail quoteDetail = new QuoteDetail();
            if(quoteDetailEntity.getTbProductFormatByPfId() != null){
                quoteDetail.setPdId((long)quoteDetailEntity.getTbProductFormatByPfId().getPfId());
                quoteDetail.setPfUnit(quoteDetailEntity.getTbProductFormatByPfId().getPfUnit());
            }
            if(quoteDetailEntity.getTbQuoteByQuoteId() != null){
                quoteDetail.setqId(quoteDetailEntity.getTbQuoteByQuoteId().getQuoteId());
            }
            quoteDetail.setQdId(quoteDetailEntity.getQdId());
            quoteDetail.setUnitPrice(quoteDetailEntity.getUnitPrice());
            quoteDetail.setAmount(quoteDetailEntity.getAmount());
            quoteDetail.setMoney(quoteDetailEntity.getMoney());
            quoteDetail.setRemarks(quoteDetailEntity.getRemarks());
            StringBuffer stringBuffer = new StringBuffer();
            if(quoteDetailEntity.getTbProductFormatByPfId() != null){
                if(quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId() != null){
                    if(quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId().getProductName() != null){
                        quoteDetail.setProductName(quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId().getProductName());
                        stringBuffer.append(quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId().getProductName());
                    }
                    if(quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId().getProductModel() != null){
                        quoteDetail.setProductModal(quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId().getProductModel());
                        stringBuffer.append("/"+quoteDetailEntity.getTbProductFormatByPfId().getTbProductByProductId().getProductModel());
                    }
                }
                if(quoteDetailEntity.getTbProductFormatByPfId().getPfName() != null){
                    quoteDetail.setPfName(quoteDetailEntity.getTbProductFormatByPfId().getPfName());
                    stringBuffer.append("/"+quoteDetailEntity.getTbProductFormatByPfId().getPfName());
                }
                if(quoteDetailEntity.getTbProductFormatByPfId().getPfUnit() != null){
                    stringBuffer.append("["+quoteDetailEntity.getTbProductFormatByPfId().getPfUnit()+"]");
                }
            }
            quoteDetail.setTitle(stringBuffer.toString());
            quoteDetails.add(quoteDetail);
        }
        return quoteDetails;
    }

    /**
     * 保存编辑报价单明细
     * @param quoteDetailEntities
     * @param id
     * @return
     * @throws ServiceException
     */
    public boolean editDetail(List<QuoteDetailEntity> quoteDetailEntities ,Long id) throws ServiceException, NotFoundException {
        QuoteEntity quoteEntity1 = load(id);
        if(quoteEntity1.getApprovalStatus() != 0L && quoteEntity1.getApprovalStatus() != 3L){
            throw new ServiceException("报价单已锁定！");
        }
        try {
            boolean b = quoteDetailService.deleteTrue(id);
            if(quoteDetailEntities != null){
                for(QuoteDetailEntity quoteDetailEntity : quoteDetailEntities){
                    quoteDetailService.add(quoteDetailEntity);
                }
            }
            QuoteEntity quoteEntity = load(id);
            return true;
        } catch (ServiceException e) {
            e.printStackTrace();
            throw new ServiceException("编辑保存失败！");
        }
    }

    public long countByUser(Long userId)throws ServiceException{
        try {
            return quoteDao.countAllByTbUserByUserIdAndIsDelete(userDao.findUserByOne(0L,userId),0L);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("统计失败");
        }
    }
    public long countByMonth()throws ServiceException{
        try {
            Calendar calendar = Calendar.getInstance();
            int year = calendar.get(Calendar.YEAR);
            int month = calendar.get(Calendar.MONTH)+1;
            System.out.println("阿森纳反对票使得房价必将："+year+","+month);
            return quoteDao.countAllByTime(year, month);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException("统计失败");
        }
    }
}
